#include <QDebug>
#include <QFile>
#include <QStringBuilder>
#include "Template.h"
#include "Include/Project.h"

Template::Template(const QString & name)
{
    QString path = QString("python%1/templates/%2.txt").arg(Plugins::Project::currentInstance()->pythonVersion()).arg(name);
    QFile file(path);
    if (file.exists()){
        file.open(QIODevice::ReadOnly);
        _content = file.readAll();
        file.close();
    }
}


Template::~Template()
{

}

QString Template::Render(const QMap<QString, QString> & items)
{
    foreach(QString key, items.keys()){
        _content = _content.replace("{"%key%"}", items[key]);
    }
    while(true){
        int startIf = -1;
        if ((startIf = _content.indexOf("{if")) == -1)
            break;

        QString name = _content.mid(startIf+3, _content.indexOf("}")-startIf-3).trimmed();
        if (name.isEmpty())
            break;

        int endIf = -1;
        QString endIfName = "{endif " % name % "}";
        if ((endIf = _content.indexOf(endIfName, startIf)) == -1)
            break;

        QString elseIfName = "{else " % name % "}";
        QString ifName = "{if " % name % "}";
        QString trueStr = "";
        QString falseStr = "";
        int elseIf = -1;
        if ((elseIf = _content.indexOf(elseIfName, startIf)) != -1 && elseIf < endIf){
            trueStr = _content.mid(startIf+ifName.length(), elseIf - startIf - ifName.length());
            falseStr = _content.mid(elseIf + elseIfName.length(), endIf - elseIf - elseIfName.length());
        } else {
            trueStr = _content.mid(startIf+ifName.length(), endIf - startIf - ifName.length());
        }
        bool res = items.contains("if-" % name) ? items["if-" % name] == "true" : false;
        _content = _content.replace(startIf, endIf - startIf + endIfName.length(), res ? trueStr : falseStr);
    }

    return _content;
}
